package flc.ast.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.RecordBean;
import flc.ast.databinding.ActivityVideoSpliceBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoSpliceActivity extends BaseAc<ActivityVideoSpliceBinding> {

    public static String videoPath;
    private String pathV1 = "";
    private String pathV2 = "";
    private Long lengthV1;
    private Long lengthV2;
    private boolean isSel = false; //true表示点击1 false表示点击2
    private List<String> listSplice=new ArrayList<>();
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_splice;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoSpliceBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivSplice1.setOnClickListener(this);
        mDataBinding.ivSpliceDelete1.setOnClickListener(this);
        mDataBinding.rlSpliceAdd1.setOnClickListener(this);
        mDataBinding.ivSplice2.setOnClickListener(this);
        mDataBinding.ivSpliceDelete2.setOnClickListener(this);
        mDataBinding.rlSpliceAdd2.setOnClickListener(this);
        mDataBinding.ivVideoSwap.setOnClickListener(this);
        mDataBinding.tvVideoSpliceDerive.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivPlayStart:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf2);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivSpliceDelete1:
                mDataBinding.rlSplice1.setVisibility(View.GONE);
                mDataBinding.rlSpliceAdd1.setVisibility(View.VISIBLE);
                pathV1="";
                break;
            case R.id.rlSpliceAdd1:
                isSel = true;
                gotoSelect();
                break;
            case R.id.ivSpliceDelete2:
                mDataBinding.rlSplice2.setVisibility(View.GONE);
                mDataBinding.rlSpliceAdd2.setVisibility(View.VISIBLE);
                pathV2="";
                break;
            case R.id.rlSpliceAdd2:
                isSel = false;
                gotoSelect();
                break;
            case R.id.ivVideoSwap:
                if (TextUtils.isEmpty(pathV1) || TextUtils.isEmpty(pathV2)) {
                    ToastUtils.showShort(R.string.please_add_video);
                } else {
                    String path = "";
                    path = pathV2;
                    pathV2 = pathV1;
                    pathV1 = path;
                    Glide.with(mContext).load(pathV1).into(mDataBinding.ivSplice1);
                    Glide.with(mContext).load(pathV2).into(mDataBinding.ivSplice2);
                }
                break;
            case R.id.tvVideoSpliceDerive:
                if (!TextUtils.isEmpty(pathV1) && !TextUtils.isEmpty(pathV2)) {
                    mDataBinding.tvVideoSpliceDerive.setEnabled(false);
                    saveVideo();
                } else {
                    ToastUtils.showShort(R.string.please_add_video);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        pathV1=videoPath;
        Glide.with(mContext).load(pathV1).into(mDataBinding.ivSplice1);
        lengthV1=videoLength;
    }

    //去视频选择界面
    private void gotoSelect() {
        Intent intent = new Intent(mContext, SelVideoActivity.class);
        intent.putExtra(Content.Again, true);
        startActivityForResult(intent, Content.Request_split);
    }

    //保存视频
    private void saveVideo() {
        listSplice.clear();
        listSplice.add(pathV1);
        listSplice.add(pathV2);
        if (listSplice.size() != 2) {
            ToastUtils.showShort(R.string.please_sel_two_video);
            return;
        }
        List<String> resultSplitLists = new ArrayList<>();
        for (String path : listSplice) {
            resultSplitLists.add(path);
        }
        EditorHolder.editor().videoMerge(resultSplitLists, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, outFilePath);//保存到手机相册
                        //保存到我的作品
                        String resultFile = FileUtil.generateFilePath(Content.myTemp, getString(R.string.unit_mp4));
                        FileUtils.copy(outFilePath, resultFile);
                        emitter.onNext(resultFile);
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        mDataBinding.tvVideoSpliceDerive.setEnabled(true);
                        ToastUtils.showShort(getString(R.string.save_to_album));
                        saveRecord(path);
                    }
                });
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                mDataBinding.tvVideoSpliceDerive.setEnabled(true);
                ToastUtils.showShort(R.string.save_failure);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.save_video_ing)
                        + progress
                        + getString(R.string.unit_percent));
            }
        });
    }

    //保存记录
    private void saveRecord(String videoPath) {
        List<RecordBean> listSave = new ArrayList<>();
        String time = TimeUtils.getNowString(new SimpleDateFormat("yyyy/MM/dd"));
        listSave.add(new RecordBean(FileUtils.getFileName(videoPath),
                TimeUtil.getMmss(MediaUtil.getDuration(videoPath)), FileUtils.getSize(videoPath),
                time, videoPath));
        List<RecordBean> listSp = SPUtil.getObject(mContext, new TypeToken<List<RecordBean>>() {
        }.getType());
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            SPUtil.putObject(mContext, listSp, new TypeToken<List<RecordBean>>() {
            }.getType());
        } else {
            SPUtil.putObject(mContext, listSave, new TypeToken<List<RecordBean>>() {
            }.getType());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Content.Request_split) {
            String path = (String) data.getSerializableExtra(Content.VideoPath);
            if (isSel) {
                pathV1 = path;
                lengthV1 = MediaUtil.getDuration(path);
                Glide.with(mContext).load(pathV1).into(mDataBinding.ivSplice1);
                mDataBinding.rlSplice1.setVisibility(View.VISIBLE);
                mDataBinding.rlSpliceAdd1.setVisibility(View.GONE);
            } else if (!isSel) {
                pathV2 = path;
                lengthV2 = MediaUtil.getDuration(path);
                Glide.with(mContext).load(pathV2).into(mDataBinding.ivSplice2);
                mDataBinding.rlSplice2.setVisibility(View.VISIBLE);
                mDataBinding.rlSpliceAdd2.setVisibility(View.GONE);
            }
            mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(lengthV1, "ss")));
            mDataBinding.tvPlayRight.setText(TimeUtil.getMmss(lengthV1));
            mDataBinding.videoView.setVideoPath(pathV1);
            mDataBinding.videoView.seekTo(1);
            mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
            mDataBinding.videoView.start();
            startTime();
        }
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf2);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置播放器
        setPlayer();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected boolean isStatusBarTextDark() {
        return false;
    }

}